﻿using System.Web;
using Newtonsoft.Json;
using SE.PO.CInterface.CuCoding.Signals;

namespace SE.PO.CInterface.Web.Clients.CuCoding;

public class SignalsCodingClient : ClientBase
{
    public SignalsCodingClient(IHttpClientFactory clientFactory, IConfiguration configuration) : base(clientFactory,
        configuration)
    {
    }

    public override string GetRoute() => "signals-coding";

    public async Task<PageData<SignalCodingDto>?> GetPageData()
    {
        var client = ClientFactory.CreateClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"{BaseUrl}/api/app/{GetRoute()}"),
        };
        using var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        var pageData = JsonConvert.DeserializeObject<PageData<SignalCodingDto>>(body);
        if (pageData != null)
        {
            return pageData;
        }

        return default;
    }

    public async Task<SignalCodingDto[]?>? Get(string monitorName = "")
    {
        var key = HttpUtility.UrlEncode(monitorName);
        var client = ClientFactory.CreateClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"{BaseUrl}/api/app/{GetRoute()}?monitorName={key}"),
        };
        using var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        var pageData = JsonConvert.DeserializeObject<PageData<SignalCodingDto>>(body);
        if (pageData != null)
        {
            return pageData.Items;
        }

        return default;
    }
}